import { useState, useEffect } from 'react';
import {
  Alert,
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  Divider,
  FormControl,
  Grid,
  IconButton,
  InputLabel,
  OutlinedInput,
  Pagination,
  Paper,
  Snackbar,
  Stack,
  TextField,
  Typography,
  Avatar,
  Tooltip
} from '@mui/material';
import {
  Send as SendIcon,
  Favorite as FavoriteIcon,
  FavoriteBorder as FavoriteBorderIcon,
  Person as PersonIcon,
  AccessTime as AccessTimeIcon,
  PushPin as PushPinIcon,
  Reply as ReplyIcon,
  Message as MessageIcon,
  EmojiEmotions as EmojiIcon
} from '@mui/icons-material';
import ToolPageTemplate from '@/components/ToolPageTemplate';
import { useMessage, MessageRequest } from '@/hooks/tools/useMessage';

console.log('MessageBoard component loading...');

const MessageBoard = () => {
  console.log('MessageBoard component rendering...');
  
  const {
    messages,
    loading,
    error,
    total,
    submitting,
    getPublicMessages,
    submitMessage,
    likeMessage,
    clearError
  } = useMessage();
  
  console.log('MessageBoard hook data:', { messages, loading, error, total });

  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error'>('success');

  // 表单状态
  const [nickname, setNickname] = useState('');
  const [email, setEmail] = useState('');
  const [content, setContent] = useState('');
  const [likedMessages, setLikedMessages] = useState<Set<number>>(new Set());

  useEffect(() => {
    loadMessages();
  }, [currentPage]);

  const loadMessages = () => {
    getPublicMessages(currentPage, pageSize);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!nickname.trim() || !content.trim()) {
      showSnackbar('请填写昵称和留言内容', 'error');
      return;
    }

    try {
      const messageData: MessageRequest = {
        nickname: nickname.trim(),
        email: email.trim() || undefined,
        content: content.trim()
      };

      await submitMessage(messageData);
      
      // 清空表单
      setNickname('');
      setEmail('');
      setContent('');
      
      showSnackbar('留言提交成功，等待审核！', 'success');
      
      // 刷新留言列表
      setTimeout(() => {
        loadMessages();
      }, 1000);
      
    } catch (err: any) {
      showSnackbar(err.message || '提交失败', 'error');
    }
  };

  const handleLike = async (messageId: number) => {
    if (likedMessages.has(messageId)) {
      showSnackbar('您已经点过赞了', 'error');
      return;
    }

    try {
      await likeMessage(messageId);
      setLikedMessages(prev => new Set([...prev, messageId]));
      showSnackbar('点赞成功！', 'success');
    } catch (err: any) {
      showSnackbar(err.message || '点赞失败', 'error');
    }
  };

  const handlePageChange = (_: React.ChangeEvent<unknown>, value: number) => {
    setCurrentPage(value);
  };

  const showSnackbar = (message: string, severity: 'success' | 'error') => {
    setSnackbarMessage(message);
    setSnackbarSeverity(severity);
    setSnackbarOpen(true);
  };

  const handleCloseSnackbar = () => {
    setSnackbarOpen(false);
  };

  const getRandomAvatarColor = (nickname: string) => {
    const colors = ['#FF9C6E', '#6B73FF', '#52C41A', '#FFA940', '#FF85C0', '#40A9FF', '#95DE64'];
    let hash = 0;
    for (let i = 0; i < nickname.length; i++) {
      hash = nickname.charCodeAt(i) + ((hash << 5) - hash);
    }
    return colors[Math.abs(hash) % colors.length];
  };

  const totalPages = Math.ceil(total / pageSize);

  return (
    <ToolPageTemplate
      title="留言板"
      description="欢迎在这里留下您的宝贵意见和建议"
      category="互动交流"
      categoryColor="#FF85C0"
    >
      {/* 快速信息区域 */}
      <Box sx={{ mb: 4 }}>
        <Stack direction="row" spacing={2} justifyContent="center" flexWrap="wrap">
          <Chip 
            icon={<MessageIcon />} 
            label="留言交流" 
            variant="outlined" 
            color="primary"
          />
          <Chip 
            icon={<EmojiIcon />} 
            label="温馨社区" 
            variant="outlined" 
            color="secondary"
          />
        </Stack>
      </Box>

      <Stack spacing={4}>
        {/* 留言提交表单 */}
        <Paper 
          elevation={0} 
          sx={{ 
            p: 4, 
            borderRadius: 3,
            border: '1px solid',
            borderColor: 'divider',
            background: 'linear-gradient(145deg, #ffffff 0%, #fafbff 100%)'
          }}
        >
          <Typography 
            variant="h6" 
            sx={{ 
              mb: 3, 
              fontWeight: 700,
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              color: '#FF85C0'
            }}
          >
            <SendIcon />
            发表留言
          </Typography>
          
          <Box component="form" onSubmit={handleSubmit}>
            <Grid container spacing={3}>
              <Grid item xs={12} sm={6}>
                <FormControl fullWidth>
                  <InputLabel>昵称 *</InputLabel>
                  <OutlinedInput
                    value={nickname}
                    onChange={(e) => setNickname(e.target.value)}
                    label="昵称 *"
                    placeholder="请输入您的昵称"
                    required
                  />
                </FormControl>
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormControl fullWidth>
                  <InputLabel>邮箱</InputLabel>
                  <OutlinedInput
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    label="邮箱"
                    placeholder="请输入您的邮箱（可选）"
                    type="email"
                  />
                </FormControl>
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  multiline
                  rows={4}
                  value={content}
                  onChange={(e) => setContent(e.target.value)}
                  label="留言内容 *"
                  placeholder="请输入您的留言内容..."
                  required
                  inputProps={{ maxLength: 1000 }}
                  helperText={`${content.length}/1000`}
                />
              </Grid>
              <Grid item xs={12}>
                <Box sx={{ textAlign: 'center' }}>
                  <Button
                    type="submit"
                    variant="contained"
                    size="large"
                    startIcon={<SendIcon />}
                    disabled={submitting || !nickname.trim() || !content.trim()}
                    sx={{
                      borderRadius: '25px',
                      px: 4,
                      py: 1.5,
                      textTransform: 'none',
                      fontWeight: 600,
                      fontSize: '1.1rem',
                      minWidth: 200,
                      background: 'linear-gradient(135deg, #FF85C0 0%, #FFADD6 100%)',
                      '&:hover': {
                        background: 'linear-gradient(135deg, #FF6BB3 0%, #FF85C0 100%)',
                      }
                    }}
                  >
                    {submitting ? '提交中...' : '发表留言'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </Box>
        </Paper>

        {/* 留言列表 */}
        <Paper 
          elevation={0} 
          sx={{ 
            borderRadius: 3,
            border: '1px solid',
            borderColor: 'divider',
            overflow: 'hidden'
          }}
        >
          <Box sx={{ p: 3, borderBottom: '1px solid', borderColor: 'divider' }}>
            <Typography 
              variant="h6" 
              sx={{ 
                fontWeight: 700,
                display: 'flex',
                alignItems: 'center',
                gap: 1,
                color: '#FF85C0'
              }}
            >
              <MessageIcon />
              留言列表 ({total})
            </Typography>
          </Box>

          {loading ? (
            <Box sx={{ p: 4, textAlign: 'center' }}>
              <Typography color="text.secondary">加载中...</Typography>
            </Box>
          ) : messages.length === 0 ? (
            <Box sx={{ p: 4, textAlign: 'center' }}>
              <Typography color="text.secondary">暂无留言，快来发表第一条留言吧！</Typography>
            </Box>
          ) : (
            <Stack>
              {messages.map((message, index) => (
                <Box key={message.id}>
                  <Card 
                    elevation={0}
                    sx={{ 
                      position: 'relative',
                      background: message.isTop 
                        ? 'linear-gradient(135deg, #FFF9E6 0%, #FFFBF0 100%)'
                        : 'transparent'
                    }}
                  >
                    {message.isTop === 1 && (
                      <Chip
                        icon={<PushPinIcon />}
                        label="置顶"
                        size="small"
                        color="warning"
                        sx={{ 
                          position: 'absolute',
                          top: 16,
                          right: 16,
                          zIndex: 1
                        }}
                      />
                    )}
                    
                    <CardContent sx={{ p: 3 }}>
                      <Stack spacing={2}>
                        {/* 用户信息 */}
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                          <Avatar 
                            sx={{ 
                              bgcolor: getRandomAvatarColor(message.nickname),
                              width: 48,
                              height: 48
                            }}
                          >
                            <PersonIcon />
                          </Avatar>
                          <Box sx={{ flex: 1 }}>
                            <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
                              {message.nickname}
                            </Typography>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              <AccessTimeIcon fontSize="small" color="action" />
                              <Typography variant="body2" color="text.secondary">
                                {message.createTimeDisplay}
                              </Typography>
                            </Box>
                          </Box>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <Tooltip title="点赞">
                              <IconButton 
                                onClick={() => handleLike(message.id)}
                                disabled={likedMessages.has(message.id)}
                                color={likedMessages.has(message.id) ? 'error' : 'default'}
                                size="small"
                              >
                                {likedMessages.has(message.id) ? 
                                  <FavoriteIcon fontSize="small" /> : 
                                  <FavoriteBorderIcon fontSize="small" />
                                }
                              </IconButton>
                            </Tooltip>
                            <Typography variant="body2" color="text.secondary">
                              {message.likeCount}
                            </Typography>
                          </Box>
                        </Box>

                        {/* 留言内容 */}
                        <Typography 
                          variant="body1" 
                          sx={{ 
                            lineHeight: 1.7,
                            whiteSpace: 'pre-wrap',
                            wordBreak: 'break-word'
                          }}
                        >
                          {message.content}
                        </Typography>

                        {/* 管理员回复 */}
                        {message.reply && (
                          <Box 
                            sx={{ 
                              mt: 2,
                              p: 2,
                              bgcolor: 'rgba(107, 115, 255, 0.05)',
                              borderRadius: 2,
                              borderLeft: '4px solid #6B73FF'
                            }}
                          >
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                              <ReplyIcon fontSize="small" color="primary" />
                              <Typography variant="subtitle2" color="primary" sx={{ fontWeight: 600 }}>
                                管理员回复
                              </Typography>
                              {message.replyTime && (
                                <Typography variant="caption" color="text.secondary">
                                  {new Date(message.replyTime).toLocaleString()}
                                </Typography>
                              )}
                            </Box>
                            <Typography 
                              variant="body2" 
                              sx={{ 
                                lineHeight: 1.6,
                                whiteSpace: 'pre-wrap'
                              }}
                            >
                              {message.reply}
                            </Typography>
                          </Box>
                        )}
                      </Stack>
                    </CardContent>
                  </Card>
                  {index < messages.length - 1 && <Divider />}
                </Box>
              ))}
            </Stack>
          )}

          {/* 分页 */}
          {totalPages > 1 && (
            <Box sx={{ p: 3, display: 'flex', justifyContent: 'center' }}>
              <Pagination
                count={totalPages}
                page={currentPage}
                onChange={handlePageChange}
                color="primary"
                shape="rounded"
                showFirstButton
                showLastButton
              />
            </Box>
          )}
        </Paper>
      </Stack>

      {/* 错误提示 */}
      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        onClose={clearError}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="error" onClose={clearError} sx={{ width: '100%' }}>
          {error}
        </Alert>
      </Snackbar>

      {/* 操作结果提示 */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert severity={snackbarSeverity} sx={{ width: '100%' }}>
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </ToolPageTemplate>
  );
};

export default MessageBoard;